import _ from 'lodash';
import { createMemoryHistory, createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import routes from './routes';
//@ts-ignore
import { defineRouter } from '#q-app/wrappers';
import useLoginInfoStore from 'src/stores/useLoginInfoStore';

export default defineRouter(function(/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === 'history'
      ? createWebHistory
      : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE)
  });


  // 全局前置守卫
  Router.beforeEach(async (to, from, next) => {
    // 如果是登录页面，直接放行
    if (to.path === '/login') {
      next();
      return;
    }

    // 检查登录状态
    try {
      const loginInfoStore = useLoginInfoStore();
      const loggedIn = await loginInfoStore.isLoggedIn(); // await LCC.isLoggedIn();

      if (loggedIn) {
        // 已登录，允许访问
        console.log('路由守卫: 用户已登录，允许访问', to.path);
        next();
      } else {
        // 未登录，重定向到登录页面
        console.log('路由守卫: 用户未登录或登录信息不完整，重定向到登录页面');
        console.log('当前路径:', to.path, '来源路径:', from.path);

        // 如果LCC对象存在，输出登录信息用于调试
        if (typeof window !== 'undefined' && window.LCC) {
          console.log('LCC登录信息:', {
            username: window.LCC.loginInfo.username,
            token: window.LCC.loginInfo.token ? '已设置' : '未设置'
          });
        }

        next('/login');
      }
    } catch (error) {
      console.error('路由守卫: 检查登录状态失败:', error);
      // 出错时重定向到登录页面
      next('/login');
    }
  });

  return Router;
});
